package com.wusiwei.security;

import io.jsonwebtoken.ExpiredJwtException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * JWT认证过滤器
 */
@Component
@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private JwtTokenUtil jwtTokenUtil;
    private UserDetailsService userDetailsService;

    // 添加无参构造函数，以便Spring可以创建实例
    public JwtAuthenticationFilter() {
    }

    // 添加带参数的构造函数，以便WebSecurityConfig可以创建实例
    public JwtAuthenticationFilter(JwtTokenUtil jwtTokenUtil, UserDetailsService userDetailsService) {
        this.jwtTokenUtil = jwtTokenUtil;
        this.userDetailsService = userDetailsService;
    }

    @Autowired
    public void setJwtTokenUtil(JwtTokenUtil jwtTokenUtil) {
        this.jwtTokenUtil = jwtTokenUtil;
    }

    @Autowired
    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        log.debug("JWT过滤器开始处理请求: {}", request.getRequestURI());

        // 检查是否是导出请求
        boolean isExportRequest = request.getRequestURI().contains("/export") &&
                "GET".equalsIgnoreCase(request.getMethod());

        if (isExportRequest) {
            log.info("处理导出请求: {}", request.getRequestURI());
        }

        try {
            String token = extractToken(request);

            if (token != null && jwtTokenUtil.validateToken(token)) {
                String username = jwtTokenUtil.getUsernameFromToken(token);
                if (username != null) {
                    log.debug("从Token中提取的用户名: {}", username);

                    // 创建Authentication对象并设置到SecurityContext
                    UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                            userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authentication);

                    log.debug("用户'{}'已认证", username);

                    // 如果是导出请求，打印认证信息
                    if (isExportRequest) {
                        log.info("导出请求已通过认证: 用户 = {}", username);
                    }
                }
            }
        } catch (ExpiredJwtException ex) {
            log.info("Token已过期: {}", ex.getMessage());

            // 特殊处理导出请求的过期Token
            if (isExportRequest) {
                log.warn("导出请求使用了过期的Token");
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write("{\"code\":401,\"message\":\"登录已过期，请重新登录后再导出\",\"success\":false}");
                return; // 不继续执行过滤器链
            }
        } catch (Exception ex) {
            log.error("无法设置用户认证", ex);
        }

        chain.doFilter(request, response);
    }

    private String extractToken(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        log.debug("Authorization header: {}", bearerToken);

        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
} 